package cn.laike.modules.dev.controller;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;

import cn.laike.common.exception.RRException;
import cn.laike.common.utils.Constant;
import cn.laike.common.utils.FileUtils;
import cn.laike.common.utils.PageUtils;
import cn.laike.common.utils.R;
import cn.laike.common.validator.ValidatorUtils;
import cn.laike.modules.dev.entity.CityEntity;
import cn.laike.modules.dev.entity.ConfigEntity;
import cn.laike.modules.dev.entity.HotelEntity;
import cn.laike.modules.dev.service.CityService;
import cn.laike.modules.dev.service.ConfigService;
import cn.laike.modules.dev.service.HotelService;
import cn.laike.modules.dev.utils.DevUtils;
import cn.laike.modules.sys.entity.SysUserEntity;
import cn.laike.modules.sys.service.SysUserService;
import cn.laike.modules.sys.shiro.ShiroUtils;



/**
 * 酒店列表
 *
 * @author ziye
 * @email 524748907@qq.com
 * @date 2019-02-18 16:57:21
 */
@RestController
@RequestMapping("dev/hotel")
public class HotelController {
    @Autowired
    private HotelService hotelService;
    
    @Autowired
    private ConfigService configService;
    
    @Autowired
    private CityService cityService;
    
    @Autowired
	private SysUserService sysUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("dev:hotel:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = hotelService.queryPage(params);

        return R.ok().put("page", page);
    }
    
    @RequestMapping("/queryHotelNameList")
    public R queryHotelNameList(@RequestParam Map<String, Object> params){
        List list = hotelService.queryHotelNameList(ShiroUtils.getUserId());
        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("dev:hotel:info")
    public R info(@PathVariable("id") Integer id){
        HotelEntity hotel = hotelService.selectById(id);

        return R.ok().put("hotel", hotel);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("dev:hotel:save")
    public R save(@RequestBody HotelEntity hotel){
    	String password = hotel.getPassword();
    	ConfigEntity config = configService.getByUid(ShiroUtils.getUserId());
    	if(config == null) {
    		 return R.error("请完善小程序配置信息！");
    	}
    	hotel.setConfigId(config.getId());
    	hotel.setConfigName(config.getName());
    	
    	CityEntity city = cityService.selectById(hotel.getCityId());
    	if(city == null) {
   		 	return R.error("请选择所属城市！");
    	}
    	if(StringUtils.isEmpty(hotel.getName())) {
    		return R.error("请输入酒店名称！");
    	}
    	if(StringUtils.isEmpty(hotel.getUsername())) {
    		return R.error("请输入账号名！");
    	}
    	if(StringUtils.isEmpty(hotel.getPassword())) {
    		return R.error("请输入密码！");
    	}
    	
    	SysUserEntity user = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
				.eq("username", hotel.getUsername()));
    	if(user != null && user.getUserId() != null && user.getUserId() > 0) {
   		 	return R.error("账号已存在！");
    	}
    	
    	
        hotel.setPassword("");
    	hotel.setCityId(city.getId());
    	hotel.setCityName(city.getName());
    	
    	hotel.setUid(config.getUid());
    	hotel.setDelFlag("0");
    	hotel.setCreateTime(new Date());
        hotelService.insert(hotel);
        
        user = new SysUserEntity();
        user.setUsername(hotel.getUsername());
        user.setPassword(password);
        user.setEmail("");
        user.setMobile(hotel.getMobile());
        user.setStatus(1);
        Long[] roleId = {2L};
        user.setRoleIdList(Arrays.asList(roleId));
        user.setDeptId(1L);
        user.setParentUserId(hotel.getUid());
        user.setHotelId(hotel.getId());
        sysUserService.save(user);
        
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("dev:hotel:update")
    public R update(@RequestBody HotelEntity hotel){
        ValidatorUtils.validateEntity(hotel);
        CityEntity city = cityService.selectById(hotel.getCityId());
    	if(city == null) {
   		 	return R.error("请选择所属城市！");
    	}
    	SysUserEntity user = sysUserService.selectOne(new EntityWrapper<SysUserEntity>()
				.eq("username", hotel.getUsername()));
    	Long[] roleId = {2L};
        user.setRoleIdList(Arrays.asList(roleId));
    	user.setPassword(hotel.getPassword());
    	sysUserService.update(user);
    	
    	hotel.setPassword("");
    	hotel.setCityId(city.getId());
    	hotel.setCityName(city.getName());
        hotelService.updateAllColumnById(hotel);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("dev:hotel:delete")
    public R delete(@RequestBody Integer[] ids){
        //hotelService.deleteBatchIds(Arrays.asList(ids));
    	List<HotelEntity> list = Lists.newArrayList();
    	for (Integer id : ids) {
    		HotelEntity hotel = new HotelEntity();
    		hotel.setId(id);
    		hotel.setDelFlag("1");
    		list.add(hotel);
		}
    	hotelService.updateBatchById(list);

        return R.ok();
    }
    
	@RequestMapping("/upload")
	public R upload(@RequestParam("picfile") MultipartFile picfile,HttpServletRequest request) throws Exception {
		if (picfile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String url = "";
		if(picfile != null && picfile.getOriginalFilename().length()>4){
			String picFilePath = DevUtils.getHotelResourceSavePath()+File.separator;
			FileUtils.createDirectory(picFilePath);
			String sname = picfile.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = "hotel"+ShiroUtils.getUserId() + "_"+System.currentTimeMillis()+fileType;
			File file = new File(picFilePath+fname);
			System.out.println("保存文件:"+picFilePath+fname);
			try {
				picfile.transferTo(file);
				url = file.getName();
			} catch (Exception e) {
				System.out.println("上传文件失败:"+picFilePath+fname);
				e.printStackTrace();
			}
		}
		return R.ok().put("url", url);
	}

}
